package com.toman.ui.my;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.toman.R;
import com.toman.Util.TimeUtil;
import com.toman.Util.ToastUtil;
import com.toman.toolbar.ToolBarWhiteActivity;
import com.toman.widget.ClearEditText;
import com.toman.widget.callback.LoadingCallback;
import com.toman.widget.callback.PostUtil;
import com.toman.widget.callback.WifiCallback;
import com.toman.wifi.Activity.EspWifiAdminSimple;
import com.toman.wifi.Activity.EsptouchDemoActivity;
import com.toman.wifi.Activity.EsptouchTask;
import com.toman.wifi.Activity.IEsptouchListener;
import com.toman.wifi.Activity.IEsptouchResult;
import com.toman.wifi.Activity.IEsptouchTask;
import com.toman.wifi.Activity.task.__IEsptouchTask;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadSir;
import com.kingja.loadsir.core.Transport;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class WifiActivity extends ToolBarWhiteActivity {

    @BindView(R.id.et_name)
   EditText etName;
    @BindView(R.id.et_pwd)
    ClearEditText etPwd;
    @BindView(R.id.rl_wifi)
    RelativeLayout rlWifi;
    private EspWifiAdminSimple mWifiAdmin;
    ConnectivityManager connectivityManager;
    NetworkInfo networkInfo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wifi);
        ButterKnife.bind(this);
        initToolBar("智能配置");
        initLoad();
        initView();

    }

    public void initLoad() {
        loadService = LoadSir.getDefault().register(this, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                // Your can change the status out of Main thread.
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        loadService.showCallback(LoadingCallback.class);
                        //do retry logic...
                        SystemClock.sleep(500);
                        //callback
                        loadService.showSuccess();
                    }
                }).start();
            }
        }).setCallBack(WifiCallback.class, new Transport() {
            @Override
            public void order(Context context, View view) {
                Toolbar mToolbar = (Toolbar) view.findViewById(R.id.id_tool_bar);
                mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        finish();
                    }
                });
                Button mButton = (Button) view.findViewById(R.id.btn_retry);
                mButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));

                    }
                });

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_save, menu);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (isWifiConnect()) {
                    String apSsid = etName.getText().toString();
                    String apPassword = etPwd.getText().toString();
                    String apBssid = mWifiAdmin.getWifiConnectedBssid();

                    if (etPwd.getText().toString().length()<8){
                        ToastUtil.makeText(getApplicationContext(), "请输入正确的wifi密码,至少8位");

                    }
                    else
                    {
                        new EsptouchAsyncTask3().execute(apSsid, apBssid, apPassword, "1");

                    }
                } else {
                    PostUtil.postCallbackDelayed(loadService, WifiCallback.class);

                }
                return false;
            }
        });

        return true;
    }

    private void initView() {
        mWifiAdmin = new EspWifiAdminSimple(this);

    }

    @Override
    protected void onResume() {
        super.onResume();
        checkwifi();
    }

    private void checkwifi() {
        if (isWifiConnect()) {
            loadService.showSuccess();
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
                ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                assert cm != null;
                NetworkInfo info = cm.getActiveNetworkInfo();
                if (info != null && info.isConnected()) {


                    try {
                        String   ssid = info.getExtraInfo().replace("\"","");
                        etName.setText(ssid);
                    } catch (Exception e) {
                        e.printStackTrace();
                        ToastUtil.error(getApplicationContext(),"获取wifi名称异常，请自行输入");
                    }

                }
            }


                //有打开
         else {
                String apSsid = mWifiAdmin.getWifiConnectedSsid();
                if (apSsid != null) {
                    etName.setText(apSsid);
                }
            }
        } else {
            PostUtil.postCallbackDelayed(loadService, WifiCallback.class);

        }
    }

    private void onEsptoucResultAddedPerform(final IEsptouchResult result) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                String text = result.getBssid() + " 连接到无线网络";
                Toast.makeText(WifiActivity.this, text,
                        Toast.LENGTH_LONG).show();
            }

        });
    }


    private IEsptouchListener myListener = new IEsptouchListener() {

        @Override
        public void onEsptouchResultAdded(final IEsptouchResult result) {
            onEsptoucResultAddedPerform(result);
        }
    };


    public boolean isWifiConnect() {
        ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return mWifi.isConnected();
    }

    private class EsptouchAsyncTask3 extends AsyncTask<String, Void, List<IEsptouchResult>> {

        private ProgressDialog mProgressDialog;

        private IEsptouchTask mEsptouchTask;

        private final Object mLock = new Object();


        @Override
        protected void onPreExecute() {
            mProgressDialog = new ProgressDialog(WifiActivity.this);
            mProgressDialog.setTitle("Wifi配置");
            mProgressDialog.setMessage("WIFI配置,请等一会儿...");
            mProgressDialog.setCanceledOnTouchOutside(false);

            mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    synchronized (mLock) {
                        if (__IEsptouchTask.DEBUG) {
                            Log.i("test", "进度对话框取消了");
                        }
                        if (mEsptouchTask != null) {
                            mEsptouchTask.interrupt();
                        }
                    }
                }
            });
            mProgressDialog.setButton(DialogInterface.BUTTON_POSITIVE,
                    "等待...", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
            mProgressDialog.show();
            mProgressDialog.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(false);
        }

        @Override
        protected List<IEsptouchResult> doInBackground(String... params) {
            int taskResultCount = -1;
            synchronized (mLock) {
                // !!!NOTICE
                String apSsid = mWifiAdmin.getWifiConnectedSsidAscii(params[0]);
                String apBssid = params[1];
                String apPassword = params[2];
                String taskResultCountStr = params[3];
                taskResultCount = Integer.parseInt(taskResultCountStr);
                mEsptouchTask = new EsptouchTask(apSsid, apBssid, apPassword, WifiActivity.this);
                mEsptouchTask.setEsptouchListener(myListener);
            }
            List<IEsptouchResult> resultList = mEsptouchTask.executeForResults(taskResultCount);
            return resultList;
        }

        @Override
        protected void onPostExecute(List<IEsptouchResult> result) {
            mProgressDialog.getButton(DialogInterface.BUTTON_POSITIVE)
                    .setEnabled(true);
            mProgressDialog.getButton(DialogInterface.BUTTON_POSITIVE).setText("确认");
            IEsptouchResult firstResult = result.get(0);
            // check whether the task is cancelled and no results received
            if (!firstResult.isCancelled()) {
                int count = 0;
                // max results to be displayed, if it is more than maxDisplayCount,
                // just show the count of redundant ones
                final int maxDisplayCount = 5;
                // the task received some results including cancelled while
                // executing before receiving enough results
                if (firstResult.isSuc()) {
                    StringBuilder sb = new StringBuilder();
                    for (IEsptouchResult resultInList : result) {
                        sb.append("智能终端成功连接WIFI\nbssid:"
                                + resultInList.getBssid()
                                + "\nMac地址:"
                                + resultInList.getInetAddress()
                                .getHostAddress() + "\n");
                        count++;
                        if (count >= maxDisplayCount) {
                            break;
                        }
                    }
                    if (count < result.size()) {
                        sb.append("\nthere's " + (result.size() - count)
                                + " more result(s) without showing\n");
                    }
                    mProgressDialog.setMessage(sb.toString());
                } else {
                    mProgressDialog.setMessage("WIFI连接 失败");

                }
            }
        }
    }
}
